<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>栈的封装</title>
	</head>
	<body>
		<script>
			// method：和某一个对象实例有联系
			// function
			function stack() {
				// 栈中的属性
				this.items = [];

				// 栈的相关操作

				// 1. 将元素压入栈
				stack.prototype.push = function (element) {
					this.items.push(element);
				};

				// 2. 从栈中取出元素,并返回该元素的值
				stack.prototype.pop = function () {
					return this.items.pop();
				};

				// 3. 查看栈顶元素
				stack.prototype.peek = function () {
					return this.items[this.items.length - 1];
				};

				// 4. 判断栈是否为空
				stack.prototype.isEmpty = function () {
					return this.items.length === 0;
				};

				// 5. 获取栈中元素的个数
				stack.prototype.size = function () {
					return this.items.length;
				};

				// 6. toString 方法
				stack.prototype.toString = function () {
					let resultString = '';
					for (let i = 0; i < this.items.length; i++) {
						resultString += this.items[i] + ' ';
					}
					return resultString;
				};
			}

			let s = new stack();

			s.push(10);
			s.push(20);
			s.push(100);
			s.push(650);
			console.log(s);

			s.pop();
			s.pop();
			console.log(s);

			console.log(s.peek());

			console.log(s.isEmpty());

			console.log(s.size());

			console.log(s.toString());
		</script>
	</body>
</html>
